package com.dsmbase.corp.flow.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.dsmbase.corp.flow.domain.Flow;

@Component
public class FlowDao {

	private JdbcTemplate jdbcTemplate;
	
	private static final String SELECT_BY_ID_SQL = "select id, name, create_time, update_time from flow where id = ?";
	private static final String SELECT_ALL_SQL = "select * from flow";
	
	@Autowired
	private DataSource dataSource;
	
	@Autowired
	public void setDataSource(DataSource ds) {
		dataSource = ds;
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	public Flow getFlowById(int id) throws SQLException {
		Object[] params = new Object[] { id };
		Flow flow = null;
		try {
			flow = (Flow) jdbcTemplate.queryForObject(SELECT_BY_ID_SQL,
					params, new FlowRowMapper());
		} catch (EmptyResultDataAccessException e) {
			throw new SQLException(e);
		}
		return flow;
	}
	
	public List<Flow> getAllFlow() throws SQLException {
		List<Flow> list = jdbcTemplate.query(SELECT_ALL_SQL, new FlowRowMapper());
		return list;
	}
	
	public class FlowRowMapper implements RowMapper<Flow> {

		public Flow mapRow(ResultSet rs, int index) throws SQLException {
			Flow flow = new Flow(rs.getInt("id"), rs.getString("name"),
					rs.getTime("create_time"), rs.getTime("update_time"));
			return flow;
		}

	}
	
}
